#!/usr/bin/env python
#coding:utf-8
#
# Copyright 2010 Close To U.
#
# Author:Darcy<http://closetou.com>
#

import os
import logging
import cgi
import hashlib
import settings
from models import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
#from google.appengine.ext.webapp import template

class MainHandler(webapp.RequestHandler):
  def get(self, url):
    _pr = pagerank.get_pagerank(url)
    result = '{"url":"%s","pagerank":%s}' % (url,_pr)
    self.response.out.write(result)
    
class UploadHandler(webapp.RequestHandler):
  def get(self):
    values = {}
    self.response.out.write('hello')
  def post(self):
    secret = self.request.POST['secret']
    if secret == settings.SECRET:
      photo_file = self.request.POST['file']
      if isinstance(photo_file, cgi.FieldStorage):
        filesize = len(photo_file.value)
        if filesize > 0 and filesize < 1048576:#1024*1024
          hash_value = hashlib.sha1(photo_file.value).hexdigest()
          b = Blobs.getbyhash(hash_value)
          if not b:
            index = Accumulator.get_or_insert(key_name='Blobs', name='Blobs')
            index.counter +=1
            index.put()
            photo = Blobs(parent=index)
            photo.blob_id = index.counter
            photo.content_type = photo_file.type
            photo.filename = photo_file.filename
            photo.size = filesize
            photo.hash_value = hash_value
            photo.blob = photo_file.value
            photo.put()
            self.response.out.write('ok')
          else:
            self.response.out.write("file existed")
        else:
          self.response.out.write("file size limited.")
      else:
        self.response.out.write("can not find the file.")
    else:
      self.response.out.write('no permission')
    
def main():
  application = webapp.WSGIApplication([('/api/upload.*', UploadHandler)],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
